package cn.yangke.basic.controller;

import cn.yangke.basic.exception.BusinessException;
import cn.yangke.basic.util.AjaxResult;
import cn.yangke.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author YangKe
 * @Date 2022/6/12 21:07
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 上传接口
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart(value = "file",required = true)MultipartFile file){
        try {
            //获取上传的文件名
            String filename = file.getOriginalFilename();
            //获取文件后缀名
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            //调用工具类的上传方法   file.getBytes()将string类型转为byte类型数组
            String path = FastdfsUtil.upload(file.getBytes(),extName);
            //返回成功的ajax,并返回路径
            return AjaxResult.getAjax().setResultObj(path);
            //处理我们自己业务的异常
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.getAjax().setSuccess(false).setMessage(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.getAjax() .setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }

    @DeleteMapping
    public AjaxResult delete(String path){
        try {
            //去除路径前面的/
            String pathTmp = path.substring(1);
            //获取组名group1
            String group = pathTmp.substring(0,pathTmp.indexOf("/"));
            //去除组名 获取文件名
            String filename = pathTmp.substring(pathTmp.indexOf("/")+1);
            //调用工具类的删除方法
            FastdfsUtil.delete(group,filename);
            return AjaxResult.getAjax();
            //处理我们自己业务的异常
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.getAjax().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.getAjax().setSuccess(false).setMessage("保存对象失败！" + e.getMessage());
        }
    }
}
